import { Component, OnInit } from '@angular/core';
import { HttpService } from '@core/services/http.service';
import { ActivatedRoute, Router } from '@angular/router';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';


import {
    FormBuilder,
    FormGroup,
    Validators,
    FormControl
} from '@angular/forms';


@Component({
    selector: 'app-course',
    templateUrl: './course.component.html',
    styleUrls: ['./course.component.less']
})
export class CourseComponent implements OnInit {

    loading = false;
    list: any = [];
    pageSize: number;
    pageIndex = 1;
    ident: string;
    IP_PORT = this.Http.IP_PORT;
    total: number;
    token: string;
    style: any = {
        top: '200px'
    };
    style1: any = {
        width: '60%',
        top: '190px'
    };
    CourseModule = false;
    AddTitle = '新增课程';
    CourName = '';
    img = '';
    id = '';
    placeholder = '';
    showCourseDetail = false;
    DetailName = '';
    CourseDataList: any = [];
    ChapterId = '';
    validateForm: FormGroup;
    checkList: any = [];
    AllCheckList;

    constructor(private Http: HttpService,
        private msg: NzMessageService,
        private confirmServ: NzModalService,
        public router: Router,
        private ActiveRoute: ActivatedRoute,
        private fb: FormBuilder, ) { }

    ngOnInit() {

        this.validateForm = this.fb.group({
            xxName: [null, [Validators.required]],
            img: [null]
        }, );

        this.getData();

    }
    // 初始化列表
    getData() {
        this.pageSize = 7;
        this.Http.getCourse({ pi: this.pageIndex, ps: this.pageSize, key: '' }).subscribe(data => {
            this.list = [];
            this.list.push({
                'cour_name': '',
                'cour_id': ''
            });
            this.list = this.list.concat(data.list);
            this.total = data.total;
        });
    }

    // 打开弹出层
    AddCourse(id) {
        if (id === undefined) {
            this.CourseModule = true;
            this.CourName = '';
            this.AddTitle = '新增课程';
            this.id = '';
        } else {
            this.CourseModule = true;
            this.AddTitle = '修改课程';
            this.id = id;
            this.Http.CatchCourse({ id: this.id }).subscribe(x => {
                this.CourName = x.course.cour_name;
                this.img =  x.course.cour_img;
            });
        }
    }

    // 关闭弹出层
    CloseCourse() {
        this.CourseModule = false;
        this.validateForm.reset();
        this.img = '';
        this.CourName = '';
    }

    // 上传图片
    fileChange($event) {
        const file: File = $event.target.files[0];
        const myReader: FileReader = new FileReader();
        const that = this;
        myReader.onloadend = (loadEvent: any) => {
            this.img = loadEvent.target.result;
        };
        myReader.readAsDataURL(file);
    }

    // 新增课程提交
    AddSubmit() {
        if (this.id === '') {
            this.Http.CourseSubmit({ cour_name: this.CourName, img: this.img }).subscribe(t => {
                this.msg.info(t.msg);
                this.getData();
            });
            this.CloseCourse();
        } else {
            this.Http.CourseEdit({ cour_name: this.CourName, img: this.img, id: this.id }).subscribe(t => {
                this.msg.info(t.msg);
                this.getData();
            });
            this.CloseCourse();
        }

    }

    // 预览章节
    previewCourse(id, name) {
        this.showCourseDetail = true;
        this.DetailName = name;
        this.ChapterId = id;
        this.Http.previewCourseChapter({ cours_id: id }).subscribe(c => {
            //  var AllData = c.list;

            for (let i = 0; i < c['list'].length; i++) {
                c['list'][i]['isChange'] = true;
                c['list'][i]['isNew'] = false;
                var val = c['list'][i];
                var list = val['checkList'];
                var temp = [];
                for (let j = 0; j < list.length; j++) {
                    var item = list[j];
                    if (item["isCheck"] === true) {
                        temp.push(item);
                    }
                }
                val['checkList'] = temp;
                c['list'][i] = val;
            }
            this.CourseDataList = [];
            this.CourseDataList = this.CourseDataList.concat(c['list']);
        });
    }

    // 修改章节
    Edit(list) {
        list.isChange = false;
        this.Http.previewCourseChapter({ cours_id: this.ChapterId }).subscribe(c => {
            const AllData = c.list;
            AllData.forEach((val, idx, array) => {
                if (val.id === list.id) {
                    list.checkList = [];
                    list.checkList = val.checkList;
                }
            });
        });
    }


    // 删除章节
    removeCourseData(list) {
        this.Http.DelCourseChapter({ id: list.id }).subscribe(z => {
            this.msg.info(z.msg);
            this.previewCourse(list.cour_id, this.DetailName);
        });
    }

    // 保存章节
    saveCourseData(list) {
        const choice = list.checkList;
        const pArr = [];
        for (let i = 0; i < choice.length; i++) {
            if (choice[i].isCheck) {
                pArr.push(choice[i].p_id);
            }
        }
        this.Http.AddCourseChapter({ cour_id: list.cour_id, id: list.id, chapter_name: list.chapter_name, pArr: pArr }).subscribe(z => {
            this.msg.info(z.msg);
            this.previewCourse(list.cour_id, this.DetailName);
        });
    }

    // 取消修改章节
    cencalSave(data, i) {
        if (data.isNew) {
            this.CourseDataList.splice(i, 1);
        } else {
            data.isChange = true;
            this.Http.previewCourseChapter({ cours_id: this.ChapterId }).subscribe(c => {
                const AllData = c.list;
                AllData.forEach((val, idx, array) => {
                    val['isChange'] = true;
                    val['isNew'] = false;
                    val.checkList.forEach((val1, idx1, array1) => {
                        if (!val1.isCheck) {
                            val.checkList.splice(idx1, 1);
                        }
                    });
                });
                this.CourseDataList = [];
                this.CourseDataList = this.CourseDataList.concat(AllData);
            });
        }
    }

    // 添加章节
    addClassData() {
        this.Http.getProject('course', { pi: 1, ps: 999 }).then(data => {
            this.AllCheckList = [];
            this.AllCheckList = this.AllCheckList.concat(data.list);
            this.CourseDataList.push({ cour_id: this.ChapterId, id: 0, chapter_name: '', isChange: false, isNew: true, checkList: this.AllCheckList });
        });
    }

    getFormControl(name) {
        return this.validateForm.controls[name];
    }

    deleteCourse(id) {
        this.confirmServ.confirm({
            title: '是否要删除该课程?',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                this.Http.Coursedelete({ id: id }).subscribe(res => {
                    this.msg.info(res.msg);
                    this.getData();
                });
            },
            onCancel() {

            }
        });

    }

}
